﻿var myChat = (function () {

    var chats = [];
    var chatKeys=[];

    function ChatConstrustor(author, chattext, timestamp) {
        this.author = author;
        this.chattext = chattext;
        this.timestamp = timestamp;
};
    //Getting chats from Firebase
    function getFirebaseChat() {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://chattycats.firebaseio.com/chat/.json', true);
        xhr.onload = function () {
            if (this.status >= 200 && this.status < 400) {
                console.log("GET sources");
                var xChat = JSON.parse(this.response);
                showFirebaseChat(xChat);

            } else {
                console.log("error");

            }
        }
        xhr.send();
    };

    function showFirebaseChat(tData) {
        var tCnt;                   // temp Contact 
        var tStr = "";              // temp string used for concat
        var tRes = $("#idChatResults");   // element to render content
        tRes.empty();               // clear the html
        contactsObj = [];           // clear the object
        chatKeys = [];           // clear the keys

        var headerString = '<tr><td>ID</td><td>Name</td><td>Email</td><td>Phone</td><td>Actions</td></tr>';
        tRes.append(headerString);
        //
        chatKeys = Object.keys(tData); // grab the keys and asign to array
        //console.log(keysArr);
        var counter = 0;
        var chatObj; // contact object from the constructor
        for (var i in tData) {
            var chat = tData[i];
            // Action buttons
            //var editBtn = '<button  onclick="myContacts.doEdit(' + counter + ')" type="button" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>Edit</button>'
            var deleteBtn = '<button onclick="myContacts.doDelete(' + counter + ' , myCbSuccess, myCbError)" type="button" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>Delete</button>'
            // creating a new Contact object
            chatObj = new ChatConstrustor(chat.author, chat.chattext, chat.timestamp);
            // add it (newly created Contacts object) to the array
            chats.push(chatObj);
            // render to screen
            tStr = "";              // clear the temp string
            tStr += "<tr>";
            tStr += "<td>" + chat.author + "</td>";
            tStr += "<td>" + chat.timestamp + "</td>";
            tStr += "<td rowspan='2'>" + deleteBtn + "</td>";
            tStr += "</tr>"
            tStr += "<tr>"
            tStr += "<td colspan ='2'>" + chat.chattext + "</td>"
            tStr += "</tr>"
            counter++;
            tRes.append(tStr);
        }

    };
    function addFirebaseChat(successCallback, errorCallback) {
        function currDate() {
            var now = new Date();
            var date = [now.getMonth() + 1, now.getDay(), now.getYear()];
            var time = [now.getHours(), now.getMinutes(), now.getSeconds()];
            for (var i = 0; i < 3; i++) {
                if (time[i] < 10) {
                    time[i] = "0" + time[i];
                }
            }
        };

        var author = $("#chatAuthor").val();
        var timestamp = currDate + " " + time;
        var chattext = $("#chatText").val();
        var objToPost = {
            "author": author,
            "timestamp": timestamp,
            "chattext": chatext,
            
        }
        
        // AJAX call for POST
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://chattycats.firebaseio.com/chat/.json', true);
        xhr.onload = function () {
            if (this.status >= 200 && this.status < 400) {
                if (successCallback && typeof (successCallback) == "function") {
                    successCallback()
                    errorCallback()
                }
                //console.log("Success!", this.response)
                getFirebaseChat();
            } else {
                console.log(" error on post")// err
            }
        }
        // convert the Object to String
        var strObject = JSON.stringify(objToPost);
        xhr.send(strObject);
    }



    return {
        addChat: addFirebaseChat,
        getChat: getFirebaseChat,
        showchat: showFirebaseChat
        
    }
})();

